package com.zzyl.nursing.service.impl;

import java.beans.Beans;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IContractService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author gziqi
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private IContractService contractService;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }
    /*


    /**
     * 入住申请
     *
     * @param checkInApplyDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否已经入住  通过查询老人身份证号码
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        String idCardNo = checkInElderDto.getIdCardNo();
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<Elder>();
        wrapper.eq(Elder::getIdCardNo, idCardNo).in(Elder::getStatus, 1, 4);
        Elder elder = elderMapper.selectOne(wrapper);

        //如果查到了老人的信息  则提示老人已经入住 直接结束流程
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已经入住");
        }
        //如果没有入住 则更新床位信息
        //先获取床位id bedId
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        Long bedId = checkInConfigDto.getBedId();
        //根据床位id查询床位
        Bed bed = bedMapper.selectById(bedId);
        //将床位状态设置到bed对象中
        bed.setBedStatus(1);
        //在将bed对象更新到数据库中
        bedMapper.updateById(bed);
        //新增或更新老人信息
        elder = updateOrInsertElder(checkInElderDto, bed);
        //新增签约办理
        //先 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        insertContract(contractNo, checkInApplyDto, elder);

        //新增入住信息(同时保存家属信息到remark字段)
        CheckIn checkIn = insertCheckInn(elder, checkInApplyDto);

        //新增入住配置
        insertCheckInConfig(checkIn.getId(), checkInApplyDto);

    }

    /**
     * 新增入住配置
     *
     * @param checkInId
     * @param checkInApplyDto
     */

    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 添加入住信息
     *
     * @param elder
     * @param checkInApplyDto
     */

    private CheckIn insertCheckInn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约信息
     *
     * @param contractNo
     * @param checkInApplyDto
     * @param elder
     */

    private void insertContract(String contractNo, CheckInApplyDto checkInApplyDto, Elder elder) {

        //创建一个合同对象 更新合同数据库字段
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(Integer.valueOf(String.valueOf(elder.getId())));
        contract.setElderName(elder.getName());
        contract.setContractNumber(contractNo);
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        LocalDateTime startDate = checkInConfigDto.getStartDate();
        contract.setStartDate(startDate);
        LocalDateTime endDate = checkInConfigDto.getEndDate();
        contract.setEndDate(endDate);
        // 设置状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        contract.setStatus(startDate.isBefore(LocalDateTime.now()) ? 0 : 1);
        //更新至数据库
        contractMapper.insert(contract);
    }


    /**
     * 新增或更新老人信息
     *
     * @param checkInElderDto
     * @param bed             checkInElderDto
     */
    private Elder updateOrInsertElder(CheckInElderDto checkInElderDto, Bed bed) {

    //判断是更新还是新增老人信息
        //根据是否存在身份证号来判断
        String idCardNo = checkInElderDto.getIdCardNo();
        //查询是否存在这个身份证号
        LambdaQueryWrapper<Elder> wrapper1=new LambdaQueryWrapper<Elder>();
        wrapper1.eq(Elder::getIdCardNo, idCardNo).ne(Elder::getStatus, 1);
        Elder elder1 = elderMapper.selectOne(wrapper1);
        if(ObjectUtils.isNotEmpty(elder1)){
            //设置老人状态信息为1(启动状态)
            elder1.setStatus(1);
            //拷贝其他的更新信息
            BeanUtils.copyProperties(checkInElderDto, elder1);
            //更新床位信息
            elder1.setBedNumber(bed.getBedNumber());
            elder1.setBedId(bed.getId());
            //根据id 更新老人信息
            elderMapper.updateById(elder1);
            return elder1;
        }else {
            //新增老人信息
            Elder elder2 = new Elder();
            BeanUtils.copyProperties(checkInElderDto, elder2);
            elder2.setStatus(1);
            elder2.setBedId(bed.getId());
            elder2.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elder2);
            return elder2;
        }

    }




    /**
     * 查询入住详情  回显
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
    CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //通过入住id查询到老人的id
        Long elderId = checkInMapper.selectById(id).getElderId();
        Elder elder = elderMapper.selectById(elderId);
        BeanUtils.copyProperties(elder, checkInElderVo);
        //查询老人年龄
        String year = elder.getBirthday().substring(0, 3);
        int elderYear = Integer.parseInt(year);
        LocalDateTime now = LocalDateTime.now();
        /*int agedOfNow = DateUtil.ageOfNow(elder.getBirthday());*/
       /*int ageByIdCard = IdcardUtil.getAgeByIdCard(elder.getBirthday());*/
        checkInElderVo.setAge(now.getYear() - elderYear);
/*    checkInElderVo.setAge(agedOfNow);*/

        //查询合同信息
        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<Contract>();
        wrapper.eq(Contract::getElderId, elderId);
        Contract contract = contractMapper.selectOne(wrapper);

        //查询入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        //查询入住开始时间 入住结束时间
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        //查询bedNumber
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        //查询配置信息
          LambdaQueryWrapper<CheckInConfig> wrapper1=new LambdaQueryWrapper();
          wrapper1.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper1);
       /* CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigById(id);*/
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);





        //转换家属列表
        //[{"kinship":"2","name":"坡口","phone":"15364569854"}]

        checkInDetailVo.setElderFamilyVoList(JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class));
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
